<template>
  <component is="a-modal" v-model:visible="visible" :width="1000" :title="title" :mask-closable="false"
    :ok-loading="loading" @cancel="close" @before-ok="submit">
    <!-- 表单信息 start -->
    <div style="max-height:70vh;over-hidden:auto;">
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <div class="flex_box" v-for="(item,index) in skuList" :key="index">
        <div style="width: 60%;">
          <a-form-item required  label="SKU">
            <a-select v-model="item.sku_id" placeholder="请选择" :allow-clear="true" >
              <a-option v-for="(item, index) of paramsData.sku" :value="item.sku"
                :label="`${item.sku}(${item.name})`" />
            </a-select>
          </a-form-item>
          <a-form-item label="数量" required v-if="item.sku_id">
            <a-input-number  mode="button" v-model="item.sku_num" placeholder="请输入" />
          </a-form-item>
        </div>
        <div style="width: 20%;margin-top: -20px;display: flex;margin-left: 20px;">
          <icon-plus-circle v-if="index== skuList.length-1" :size="34" class="add" @click="addSku(index)"  />
          <icon-minus-circle v-if="index!=0"  :size="34" class="mini" @click="delSku(index)" />
        </div>
      </div>
      <a-form-item field="cate_id" label="分类">
        <a-select v-model="formData.cate_id" placeholder="请选择" :allow-clear="true" style="width: 60%;">
          <a-option v-for="(item, index) of paramsData.cate" :value="item.id"
            :label="`${item.floor==1?'----':''}${item.name}`" />
        </a-select>
      </a-form-item>
      <a-form-item label="版本" field="area_type">
        <sa-radio :data="paramsData.area_type" v-model="formData.area_type" placeholder="请选择"></sa-radio>
      </a-form-item>
      <a-form-item label="类型" field="type">
        <sa-radio :data="paramsData.type" v-model="formData.type" placeholder="请选择"></sa-radio>
      </a-form-item>
      <a-form-item label="是否缺货" field="stock_state">
        <sa-radio :data="ENUMS.IS" v-model="formData.stock_state" placeholder="请选择"></sa-radio>
      </a-form-item>
      <a-form-item label="中文简体名称" field="name">
        <a-input v-model="formData.name" placeholder="请输入" style="width: 60%">
        </a-input>
      </a-form-item>
      <a-form-item label="单价(美元)" field="price">
        <a-input-number mode="button" style="width: 60%;" v-model="formData.price" placeholder="请输入">
        </a-input-number>
      </a-form-item>
      <a-form-item label="单价(人民币)" field="price_cny">
        <a-input-number mode="button" style="width: 60%;" v-model="formData.price_cny" placeholder="请输入">
        </a-input-number>
      </a-form-item>
      <a-form-item label="支付选項" field="pay_coin">
        <sa-radio :titleKey="'lable'" :data="PAYITEM" v-model="formData.pay_coin" placeholder="请选择"></sa-radio>
      </a-form-item>
      <a-form-item label="排序" field="sort">
        <a-input-number mode="button" style="width: 60%;" v-model="formData.sort" placeholder="请输入,数值大排前面" />
      </a-form-item>
      <a-form-item label="状态" field="state">
        <sa-radio :data="ENUMS.STATE" v-model="formData.state" placeholder="请选择"></sa-radio>
      </a-form-item>
      <a-form-item label="封面图" required>
        <sa-upload-image :limit="1" v-model="formData.thumb_photo"></sa-upload-image>
      </a-form-item>
      <a-form-item label="轮播图" required>
        <sa-upload-image :limit="3" :multiple="true" v-model="formData.img" :tip="'至多三张'"></sa-upload-image>
      </a-form-item>
      <a-form-item label="中文简体简述" field="desc">
        <a-textarea v-model="formData.desc" placeholder="请输入"></a-textarea>
      </a-form-item>
      <a-form-item label="中文简体详情" field="details">
        <ma-wangEditor v-model="formData.details"></ma-wangEditor>
      </a-form-item>
      <a-form-item label="中文简体标签" field="lable">
        <a-input v-model="formData.lable" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </div>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import SaRadio from '@cps/sa-radio/index.vue'
import SaUploadImage from '@cps/sa-upload-image/index.vue'
import MaWangEditor from '@cps/ma-wangEditor/index.vue'
import mallApi from '@/api/system/mall'
import ENUMS from '@/utils/enums'
import tool from '@/utils/tool';
import { throttle } from 'lodash'
const paramsData = ref([])
const skuList =ref([ { sku_id: '', sku_num: 1 } ])
const getParams = async (id) => {
  const { data } = await mallApi.addGoodsParams()
  paramsData.value = { ...data }
  paramsData.value.area_type = tool.simpleTransformArray(data.area_type)
  paramsData.value.type = tool.simpleTransformArray(data.type)
}
const PAYITEM  =[
  {value:'usdt',lable:'U豆/糖果支付'},
  {value:'points',lable:'购物金/兑换积分支付'},
  {value:'usdt2',lable:'W宝/W金'},
  {value:'points2',lable:'二代购物金/兑换积分支付'},
]
const emit = defineEmits(['success'])
// 引用定义
const formRef = ref()
const mode = ref('')
const visible = ref(false)
const loading = ref(false)
let title = computed(() => {
  return (mode.value == 'add' ? '新增' : '编辑')
})
// 表单信息
const formData = reactive({
  sku_id: [],
  sku_num:[],
  cate_id:undefined,
  state: 1,
  type:'vip',
  area_type:0,
  sort: 0,
  stock_state:0,
  name: '',
  price_cny:0,
  pay_coin:'usdt',
  price:0,
  thumb_photo:'',
  img:[],
  state:1,
  desc:'',
  details:'',
  fenxiao:0,
  freight:0,
  is_hot:0,
  pageview:0,
  number:100000,
  id: '',
  lable:'',
})
// 验证规则
const rules = ref({
  sku_id: [{ required: true, message: '请选择' }],
  cate_id: [{ required: true, message: '请选择' }],
  sku_num: [{ required: true, message: '请输入' }],
  area_type:[{ required: true, message: '请选择' }],
  type:[{ required: true, message: '请选择' }],
  stock_state:[{ required: true, message: '请选择' }],
  name: [{ required: true, message: '请输入' }],
  price: [{ required: true, message: '请输入' }],
  price_cny:[{ required: true, message: '请输入' }],
  pay_coin:[{ required: true, message: '请选择' }],
  state:[{ required: true, message: '请选择' }],
  sort: [{ required: true, message: '请输入' }],
  details: [{ required: true, message: '请输入' }],
  desc: [{ required: true, message: '请输入' }],
});
// 打开弹框
const open = async (type = 'add', id = '') => {
  mode.value = type
  visible.value = true
  formRef.value.resetFields()
  await initPage()
  await getParams()
  if (type == 'add') {
    skuList.value=[ { sku_id: '', sku_num: 1 } ]
  } else {
    formData.id = id
  }

}
// 初始化页面数据
const initPage = async () => {
}

// 设置数据
const setFormData = async (data) => {
  skuList.value = data.sku_list.map(item => ({sku_id:item.sku ,sku: item.sku, sku_num: Number(item.num),sku_name:item.sku_name }))
  for (const key in formData) {
    formData.img = [...data.image_arr]
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
      if(key=='price' || key=='price_cny'){
        formData[key] = Number(data[key])
      }   
    }
    
  }
  console.log('111', formData);
}

// 数据保存
const submit = throttle(async (done) => {
  if(!skuList.value[0].sku_id){
    Message.error('请选择SKU')
    done(false)
    return
  }
  formData.sku_id=[]
  formData.sku_num=[]
  skuList.value.forEach(item => {
    formData.sku_id.push(item.sku_id)
    formData.sku_num.push(item.sku_num)
  })
  console.log('111', formData);
  if(!formData.thumb_photo){
    Message.error('请上传封面图')
    done(false)
    return
  }else if(formData.img.length<1){
    Message.error('请上传至少一张轮播图')
    done(false)
    return
  }
  
  const validate = await formRef.value?.validate()
  if (!validate) {
    loading.value = true
    try {
      let data = { ...formData }
      data.img=data.img.join('|')
      let result = {}
      console.log('data',data);
      if (mode.value === 'add') {
        // 添加数据
        data.id = ''
        result = await mallApi.addGoods(data)
      } else {
        // 修改数据
        result = await mallApi.updateGoods(data)
      }
      if (result.code === 200) {
        Message.success('操作成功')
        emit('success')
        done(true)
      }
      // 防止连续点击提交
      setTimeout(() => {
        loading.value = false
      }, 500)
    } catch {
      loading.value = false
    }
  }
  done(false)
}, 100)
const addSku = (index) => {
  skuList.value.push({ sku_id: null, sku_num: 1 });
}
const delSku = (index) => {
  if (skuList.value.length > 1) {
        skuList.value.splice(index, 1);
  }
}
// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>
<style lang="less" scoped>

.flex_box{
  height: 100%;
  display: flex;
  align-items: center;
}
.add{
  color:#1e90ff;cursor: pointer;
}
.add:hover{
  color:#4263eb;cursor: pointer;
}
.mini{
  color:#ffa8a8;cursor: pointer;
}
.mini:hover{
  color:#f03e3e;cursor: pointer;
}
</style>
